<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>冒泡与快排对比</title>
  </head>
  <body>
    <script>
      // Array新方法
      var arr = Array(100)
        .fill()
        .map((item) => Math.floor(Math.random() * 99) + 1);

      function quickSort(arr) {
        if (arr.length <= 1) {
          return arr;
        }

        var middleIndex = Math.floor(arr.length / 2);
        var middleItem = arr.splice(middleIndex, 1)[0];
        var left = [];
        var right = [];

        arr.forEach((item) => {
          if (item > middleItem) {
            right.push(item);
          } else {
            left.push(item);
          }
        });

        // return quickSort(left).concat([middleItem], quickSort(right));
        return [...quickSort(left), middleItem, ...quickSort(right)];
      }
      console.time("quick");
      console.log(quickSort(arr));
      console.timeEnd("quick");

      function BubbleSort(arr) {
        for (var i = 0; i < arr.length - 1; i++) {
          for (var j = 0; j < arr.length - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
              [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
            }
          }
        }
        return arr;
      }
      console.time("bubble");
      console.log(BubbleSort(arr));
      console.timeEnd("bubble");
    </script>
  </body>
</html>
